package it.unibz.easytravel.travel;


import java.util.ArrayList;
import java.util.List;

import it.unibz.easytravel.R;
import it.unibz.easytravel.common.Person;
import it.unibz.easytravel.db.TravelDbAdapter;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts;
import android.provider.Contacts.People;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;


public class EditTravel extends Activity {

	public static final String PREFS_NAME = "EasyTravelPrefsFile";
	public static final String TRAVEL_ID = "current_travel_id";

	private static List<Travel> travels;
	private static List<Person> members;
	private static int viewedTravelId;
	private static int viewedTravelPlace;
	private static int scoosenTravelId;

	private static EditTravel activity;
	private static Button button_next;
	private static Button button_previous;
	private static Button button_delete;
	private static Button button_edit;
	private static Button button_create;
	private static Button button_save;
	private static Button button_cancel;
	private static Button button_addMember;
	private static Button button_choose;
	private static TextView textTitle;
	private static TextView textDescription;
	private static TextView textMembers;
	private static ScrollView scroll_view_description;
	private static ScrollView scroll_view_members;
	private static ScrollView scroll_edit_description;
	private static TextView view_title;
	private static EditText edit_title;
	private static EditText edit_description;
	private static LinearLayout edit_layout;
	private static LinearLayout edit_layout_mem;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.travel_editor);
		this.activity = this;

		button_next = (Button) findViewById(R.id.travel_edit_next);
		button_next.setOnClickListener(nextTravelButtonListener);

		button_previous = (Button) findViewById(R.id.travel_edit_previous);
		button_previous.setOnClickListener(previousTravelButtonListener);

		button_create = (Button) findViewById(R.id.travel_edit_create);
		button_create.setOnClickListener(createTravelListener);

		button_delete = (Button) findViewById(R.id.travel_edit_delete);

		button_edit = (Button) findViewById(R.id.travel_edit_edit);
		button_edit.setOnClickListener(editTravelListener);

		button_save = (Button) findViewById(R.id.travel_edit_save);
		button_save.setOnClickListener(saveTravelListener);

		button_cancel= (Button) findViewById(R.id.travel_edit_cancel);
		button_cancel.setOnClickListener(cancelTravelListener);

		button_choose= (Button) findViewById(R.id.travel_edit_choose);
		button_choose.setOnClickListener(chooseTravelListener);

		button_addMember= (Button) findViewById(R.id.travel_edit_addMember);
		button_addMember.setOnClickListener(new AddTravelersButtonListener(this));


		scroll_view_description = (ScrollView) findViewById(R.id.travel_edit_scrollShow);
		scroll_view_members = (ScrollView) findViewById(R.id.travel_edit_scrollShowMembers);
		scroll_edit_description = (ScrollView) findViewById(R.id.travel_edit_scrollEdit);
		edit_layout_mem = (LinearLayout) findViewById(R.id.travel_edit_mem);


		view_title = (TextView)findViewById(R.id.travel_edit_title);
		edit_title = (EditText)findViewById(R.id.table_edit_editTitle);
		edit_description = (EditText)findViewById(R.id.table_edit_editDescription);

		edit_layout = (LinearLayout) findViewById(R.id.travel_edit_editMembers);


		textTitle = (TextView) findViewById(R.id.travel_edit_title);
		textDescription = (TextView) findViewById(R.id.travel_edit_description);
		textMembers = (TextView) findViewById(R.id.travel_edit_members);

		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		scoosenTravelId = settings.getInt(TRAVEL_ID, -1);
	}

	@Override
	protected void onResume() {
		super.onResume();
		display();
	}

	@Override
	public void finishFromChild(Activity child) {
		super.finishFromChild(child);
		TravelDbAdapter mTravelAdapter = new TravelDbAdapter(this);
		mTravelAdapter.open();
		Cursor cur = mTravelAdapter.getTravels();
		mTravelAdapter.close();
		if(cur.getCount()==0){
			finish();
		}else{
			display();
		}

	}
	
	void display(){
		travels = new ArrayList<Travel>();
		TravelDbAdapter mTravelAdapter = new TravelDbAdapter(this);
		mTravelAdapter.open();

		Cursor cur = mTravelAdapter.getTravels();
		int counter = 0;
		while (cur.moveToNext()) {

			travels.add(new Travel(
					cur.getInt(cur.getColumnIndexOrThrow(TravelDbAdapter.TRAVEL_ID)),
					cur.getString(cur.getColumnIndexOrThrow(TravelDbAdapter.TITLE)),
					cur.getString(cur.getColumnIndexOrThrow(TravelDbAdapter.DESCRIPTION)),
					cur.getInt(cur.getColumnIndexOrThrow(TravelDbAdapter.CREATOR_ID)),
					this
			));
			if(cur.getInt(cur.getColumnIndexOrThrow(TravelDbAdapter.TRAVEL_ID))==scoosenTravelId)
				viewedTravelPlace = counter;
			counter++;
		}
		mTravelAdapter.close();

		if(travels.size() > 0){
			viewedTravelId=travels.get(viewedTravelPlace).getTravelId();
			doIt();
		}else{
			Intent intent = new Intent(EditTravel.this, AddTravel.class);
			startActivity(intent);
		}
	}

	private OnClickListener saveTravelListener = new OnClickListener() {
		public void onClick(View v) {
			setViewable();
			String title =  edit_title.getText().toString();
			String description =  edit_description.getText().toString();
			int travel_id = travels.get(viewedTravelPlace).getTravelId();

			Travel travel = new Travel(travel_id, title, description, travels.get(viewedTravelPlace).getCreator(), members);

			TravelDbAdapter mTravelAdapter = new TravelDbAdapter(activity);
			mTravelAdapter.open();
			boolean updated = mTravelAdapter.updateTravel(travel, activity);
			mTravelAdapter.close();

			//TODO add informative message 
			//if(updated)

			activity.display();
		}
	};

	private void StoreChosenTravelInPrefs() {
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt(TRAVEL_ID, travels.get(viewedTravelPlace).getTravelId());

		editor.commit();
	}
	
	//TODO
	private OnClickListener chooseTravelListener = new OnClickListener() {
		public void onClick(View v) {
			
			StoreChosenTravelInPrefs();

			Toast.makeText(getBaseContext(), "Travel marked as Current..",
					Toast.LENGTH_SHORT).show();
			activity.doIt();
		}
	};

	private OnClickListener cancelTravelListener = new OnClickListener() {
		public void onClick(View v) {
			setViewable();
			activity.doIt();
		}
	};

	private OnClickListener createTravelListener = new OnClickListener() {
		public void onClick(View v) {
			Intent intent = new Intent(EditTravel.this, AddTravel.class);
			startActivity(intent);
		}
	};

	private static class deleteTravelListener implements OnClickListener {

		private int id;
		private EditTravel activity;

		public deleteTravelListener(int id, EditTravel activity) {
			this.id = id;
			this.activity = activity;
		}

		public void onClick(View v) {
			TravelDbAdapter mAdapter = new TravelDbAdapter(activity);
			mAdapter.open();
			mAdapter.delete(id, activity);
			mAdapter.close();

			activity.display();

			Toast.makeText(activity, "deleted", Toast.LENGTH_SHORT).show();
		}
	}

	private OnClickListener editTravelListener = new OnClickListener() {
		public void onClick(View v) {
			button_edit.setVisibility(Button.INVISIBLE);
			button_delete.setVisibility(Button.INVISIBLE);
			button_create.setVisibility(Button.INVISIBLE);
			button_previous.setVisibility(Button.INVISIBLE);
			button_next.setVisibility(Button.INVISIBLE);
			button_choose.setVisibility(Button.INVISIBLE);
			scroll_view_description.setVisibility(ScrollView.INVISIBLE);
			scroll_view_members.setVisibility(ScrollView.INVISIBLE);
			view_title.setVisibility(TextView.INVISIBLE);

			button_save.setVisibility(Button.VISIBLE);
			button_cancel.setVisibility(Button.VISIBLE);
			scroll_edit_description.setVisibility(ScrollView.VISIBLE);
			edit_title.setVisibility(EditText.VISIBLE);
			edit_layout.setVisibility(LinearLayout.VISIBLE);

			edit_title.setText(travels.get(viewedTravelPlace).getTitle());
			edit_description.setText(travels.get(viewedTravelPlace).getDescription());

			members = new ArrayList<Person>(travels.get(viewedTravelPlace).getTravellers());
			setTravelersToAdd();
		}
	};

	private OnClickListener previousTravelButtonListener = new OnClickListener() {
		public void onClick(View v) {
			viewedTravelPlace --;
			//last element
			if(viewedTravelPlace == 0){
				viewedTravelId=travels.get(viewedTravelPlace).getTravelId();
			}
			doIt();
		}
	};

	private OnClickListener nextTravelButtonListener = new OnClickListener() {
		public void onClick(View v) {
			viewedTravelPlace ++;
			//last element
			if(viewedTravelPlace == travels.size()-1){
				viewedTravelId=travels.get(viewedTravelPlace).getTravelId();
			}
			doIt();
		}
	};


	private static void doIt() {
		if(viewedTravelPlace == travels.size()-1){
			button_next.setVisibility(Button.INVISIBLE);
		}else{
			button_next.setVisibility(Button.VISIBLE);
		}

		if(viewedTravelPlace == 0){
			button_previous.setVisibility(Button.INVISIBLE);
		}else{
			button_previous.setVisibility(Button.VISIBLE);
		}


		textTitle.setText(travels.get(viewedTravelPlace).getTitle());

		textDescription.setText(travels.get(viewedTravelPlace).getDescription());

		List<Person> tmp_members = new ArrayList<Person>();
		tmp_members = travels.get(viewedTravelPlace).getTravellers();
		int size = tmp_members.size();
		String tmp = "";
		for (int i = 0; i < size; i++)
			tmp += tmp_members.get(i).getName()+"\n";
		textMembers.setText(tmp);

		button_delete.setOnClickListener(new deleteTravelListener(travels.get(viewedTravelPlace).getTravelId(), activity));

	}

	protected void setViewable() {
		button_edit.setVisibility(Button.VISIBLE);
		button_delete.setVisibility(Button.VISIBLE);
		button_create.setVisibility(Button.VISIBLE);
		button_previous.setVisibility(Button.VISIBLE);
		button_next.setVisibility(Button.VISIBLE);
		button_choose.setVisibility(Button.VISIBLE);
		scroll_view_description.setVisibility(ScrollView.VISIBLE);
		scroll_view_members.setVisibility(ScrollView.VISIBLE);

		view_title.setVisibility(TextView.VISIBLE);


		button_save.setVisibility(Button.INVISIBLE);
		button_cancel.setVisibility(Button.INVISIBLE);
		scroll_edit_description.setVisibility(ScrollView.INVISIBLE);
		edit_title.setVisibility(EditText.INVISIBLE);
		edit_layout.setVisibility(LinearLayout.INVISIBLE);
	}

	private class AddTravelersButtonListener implements OnClickListener {

		private Activity context;

		public AddTravelersButtonListener(Activity ctx) {
			this.context = ctx;
		}

		public void onClick(View v) {
			Intent intent = new Intent(Intent.ACTION_PICK, Contacts.People.CONTENT_URI);
			startActivityForResult(intent,0);

		}
	};



	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 0) {
			// and new traveller
			if (resultCode == RESULT_OK) {
				Cursor cur = managedQuery(data.getData(), null, null, null, null);
				if (cur.moveToFirst()) {
					int nameColumn = cur.getColumnIndexOrThrow(People.NAME); 
					int numberColumn = cur.getColumnIndexOrThrow(People.NUMBER);

					// Get the field values
					String personName = cur.getString(nameColumn);
					String personNumber = cur.getString(numberColumn);

					if(!isInTravellersList(personNumber))
						members.add(new Person(personName, personNumber));
				}

				setTravelersToAdd();
			}
		}
	}

	public static void setTravelersToAdd(){

		edit_layout_mem.removeAllViews();

		int size = members.size();
		for (int i = 0; i < size; i++) {

			LinearLayout l = new LinearLayout(activity);

			TextView text = new TextView(activity); 
			text.setText(members.get(i).getName());

			Button button = new Button(activity);
			button.setOnClickListener(new mClickedRemoveTravelerListener(members.get(i).getPhoneNumber(), activity));
			button.setBackgroundResource(R.drawable.delete);

			l.addView( text);
			l.addView( button);

			edit_layout_mem.addView(l);	
		}
	}

	public static class mClickedRemoveTravelerListener implements OnClickListener {

		private String phoneNr;
		private Activity activity;

		public mClickedRemoveTravelerListener(String phoneNr, Activity activity) {
			this.phoneNr = phoneNr;
			this.activity = activity;
		}

		public void onClick(View v) {
			int size = members.size();
			for (int i = 0; i < size; i++) {
				if(members.get(i).getPhoneNumber().equals(phoneNr)){
					members.remove(i);
					break;
				}
			}
			setTravelersToAdd();
		}
	}

	/**
	 * Checks if person is already added in the travellers list
	 * @param telephone number
	 * @return true - if number is in the list, folse - otherwise
	 */
	protected boolean isInTravellersList(String number){
		int size = members.size();
		for (int i = 0; i < size; i++)
			if(members.get(i).getPhoneNumber().equals(number))
				return true;
		return false;
	}

}
